<template>
  <a-table
    :columns="columns"
    :data="tempOkrData"
    :pagination="false"
    :bordered="{ wrapper: true, cell: true }"
    stripe
    :spanMethod="dataSpanMethod"
    :row-selection="showRowSelection ? {} : null"
    v-model:selectedKeys="selectedKeys"
    span-all
    :row-key="'id'"
    @select="select"
  >
    <template #td="{ record, column }">
      <td
        :class="[
          column.dataIndex === 'index' && record.operate === 2
            ? 'add'
            : column.dataIndex === 'index' && record.operate === 3
            ? 'update'
            : (column.dataIndex === 'index' && record.operate === 4) ||
              (column.dataIndex === 'index' &&
                record.state === 2 &&
                templateData?.optionStatus === 4)
            ? 'del'
            : ''
        ]"
      />
    </template>
    <template #index="{ record }">
      {{ record.index }}
    </template>
    <template #maxScore>
      {{ upperLimitScore ? upperLimitScore : '无限' }}
    </template>
    <template #achievementWeight="{ record }">
      {{ record.achievementWeight }}%
    </template>
    <template #owerScorerName="{ record }">
      {{ record.owerScorer?.userName }}
    </template>
    <template #owerScorerWeight="{ record }">
      {{
        record.owerScorer?.weight
          ? `${props.templateData?.selfEvaluation} %`
          : ''
      }}
      <!-- {{ record.owerScorer?.weight }} -->
    </template>
    <template #owerScorerMark="{ record }">
      <div
        v-if="
          props.args.showScoreInput &&
          record.owerScorer &&
          record.owerScorer.scoreIndex >= 0 &&
          (record.owerScorer.userId === userId ||
            record.owerScorer.isWaitDone === 1) &&
          templateData?.optionStatus === 8
        "
      >
        <a-input-number
          style="height: 100%"
          placeholder="评分"
          hide-button
          v-model="
            tableData[record.indexRow].personnelKeyResultsIndexLibrary[
              record.indexLibrary
            ].scorer[record.owerScorer.scoreIndex].score
          "
        />
      </div>
      <div v-else>{{ record.owerScorer?.score }}</div>
    </template>
    <template #owerScorerNote="{ record }">
      <div
        v-if="
          props.args.showScoreInput &&
          record.owerScorer &&
          record.owerScorer.scoreIndex >= 0 &&
          (record.owerScorer.userId === userId ||
            record.owerScorer.isWaitDone === 1) &&
          templateData?.optionStatus === 8
        "
      >
        <a-textarea
          style="height: 100%"
          auto-size
          placeholder="评分说明"
          allow-clear
          v-model="
            tableData[record.indexRow].personnelKeyResultsIndexLibrary[
              record.indexLibrary
            ].scorer[record.owerScorer.scoreIndex].note
          "
        />
      </div>
      <div v-else>{{ record.owerScorer?.note }}</div>
    </template>
    <!-- ppp -->
    <template #appointScorerName="{ record }">
      {{ record.appointScorer?.userName }}
      {{
        record.appointScorer?.weight
          ? `(${record.appointScorer?.weight} %)`
          : ''
      }}
    </template>
    <template #appointScorerWeight="{ record }">
      {{
        record.scorerStatus?.appoint?.weight
          ? `${record.scorerStatus.appoint?.weight} %`
          : ''
      }}
    </template>
    <template #appointScorerMark="{ record }">
      <div
        v-if="
          props.args.showScoreInput &&
          record.appointScorer &&
          record.appointScorer.scoreIndex >= 0 &&
          (record.appointScorer.userId === userId ||
            record.appointScorer.isWaitDone === 1) &&
          templateData?.optionStatus === 9
        "
      >
        <a-input-number
          placeholder="评分"
          hide-button
          v-model="
            tableData[record.indexRow].personnelKeyResultsIndexLibrary[
              record.indexLibrary
            ].scorer[record.appointScorer.scoreIndex].score
          "
        />
      </div>
      <div v-else>{{ record.appointScorer?.score }}</div>
    </template>
    <template #appointScorerNote="{ record }">
      <div
        v-if="
          props.args.showScoreInput &&
          record.appointScorer &&
          record.appointScorer.scoreIndex >= 0 &&
          (record.appointScorer.userId === userId ||
            record.appointScorer.isWaitDone === 1) &&
          templateData?.optionStatus === 9
        "
      >
        <a-textarea
          style="height: 100%"
          auto-size
          placeholder="评分说明"
          allow-clear
          v-model="
            tableData[record.indexRow].personnelKeyResultsIndexLibrary[
              record.indexLibrary
            ].scorer[record.appointScorer.scoreIndex].note
          "
        />
      </div>
      <div v-else>{{ record.appointScorer?.note }}</div>
    </template>
    <!-- ppp -->
    <template #superiorsScorerName="{ record }">
      {{ record.superiorsScorer?.userName }}
      {{
        record.superiorsScorer?.weight
          ? `(${record.superiorsScorer?.weight} %)`
          : ''
      }}
    </template>
    <template #superiorsScorerNote="{ record }">
      <div
        v-if="
          props.args.showScoreInput &&
          record.superiorsScorer &&
          record.superiorsScorer.scoreIndex >= 0 &&
          (record.superiorsScorer.userId === userId ||
            record.superiorsScorer.isWaitDone === 1) &&
          templateData?.optionStatus === 9
        "
      >
        <a-textarea
          style="height: 100%"
          auto-size
          placeholder="评分说明"
          allow-clear
          v-model="
            tableData[record.indexRow].personnelKeyResultsIndexLibrary[
              record.indexLibrary
            ].scorer[record.superiorsScorer.scoreIndex].note
          "
        />
      </div>
      <div v-else>{{ record.superiorsScorer?.note }}</div>
    </template>
    <template #superiorsScorerWeight="{ record }">
      {{
        record.scorerStatus?.superiors?.weight
          ? `${record.scorerStatus.superiors?.weight} %`
          : ''
      }}
    </template>
    <template #superiorsScorerMark="{ record }">
      <div
        v-if="
          props.args.showScoreInput &&
          record.superiorsScorer &&
          record.superiorsScorer.scoreIndex >= 0 &&
          (record.superiorsScorer.userId === userId ||
            record.superiorsScorer.isWaitDone === 1) &&
          templateData?.optionStatus === 9
        "
      >
        <a-input-number
          placeholder="评分"
          hide-button
          v-model="
            tableData[record.indexRow].personnelKeyResultsIndexLibrary[
              record.indexLibrary
            ].scorer[record.superiorsScorer.scoreIndex].score
          "
        />
      </div>
      <div v-else>{{ record.superiorsScorer?.score }}</div>
    </template>
    <!-- 同级 -->
    <template #peerScorerName="{ record }">
      {{ record.peerScorer?.userName }}
      {{ record.peerScorer?.weight ? `(${record.peerScorer?.weight} %)` : '' }}
    </template>
    <template #peerScorerNote="{ record }">
      <div
        v-if="
          props.args.showScoreInput &&
          record.peerScorer &&
          record.peerScorer.scoreIndex >= 0 &&
          (record.peerScorer.userId === userId ||
            record.peerScorer.isWaitDone === 1) &&
          templateData?.optionStatus === 9
        "
      >
        <a-textarea
          style="height: 100%"
          auto-size
          placeholder="评分说明"
          allow-clear
          v-model="
            tableData[record.indexRow].personnelKeyResultsIndexLibrary[
              record.indexLibrary
            ].scorer[record.peerScorer.scoreIndex].note
          "
        />
      </div>
      <div v-else>{{ record.peerScorer?.note }}</div>
    </template>
    <template #peerScorerWeight="{ record }">
      {{
        record.scorerStatus?.peer?.weight
          ? `${record.scorerStatus.peer?.weight} %`
          : ''
      }}
    </template>
    <template #peerScorerMark="{ record }">
      <div
        v-if="
          props.args.showScoreInput &&
          record.peerScorer &&
          record.peerScorer.scoreIndex >= 0 &&
          (record.peerScorer.userId === userId ||
            record.peerScorer.isWaitDone === 1) &&
          templateData?.optionStatus === 9
        "
      >
        <a-input-number
          placeholder="评分"
          hide-button
          v-model="
            tableData[record.indexRow].personnelKeyResultsIndexLibrary[
              record.indexLibrary
            ].scorer[record.peerScorer.scoreIndex].score
          "
        />
      </div>
      <div v-else>{{ record.peerScorer?.score }}</div>
    </template>
    <!-- 下级 -->
    <template #juniorScorerName="{ record }">
      {{ record.juniorScorer?.userName }}
      {{
        record.juniorScorer?.weight ? `(${record.juniorScorer?.weight} %)` : ''
      }}
    </template>
    <template #juniorScorerWeight="{ record }">
      {{
        record.scorerStatus?.junior?.weight
          ? `${record.scorerStatus.junior?.weight} %`
          : ''
      }}
    </template>
    <template #juniorScorerMark="{ record }">
      <div
        v-if="
          props.args.showScoreInput &&
          record.juniorScorer &&
          record.juniorScorer.scoreIndex >= 0 &&
          (record.juniorScorer.userId === userId ||
            record.juniorScorer.isWaitDone === 1) &&
          templateData?.optionStatus === 9
        "
      >
        <a-input-number
          placeholder="评分"
          hide-button
          v-model="
            tableData[record.indexRow].personnelKeyResultsIndexLibrary[
              record.indexLibrary
            ].scorer[record.juniorScorer.scoreIndex].score
          "
        />
      </div>
      <div v-else>{{ record.juniorScorer?.score }}</div>
    </template>
    <template #juniorScorerNote="{ record }">
      <div
        v-if="
          props.args.showScoreInput &&
          record.juniorScorer &&
          record.juniorScorer.scoreIndex >= 0 &&
          (record.juniorScorer.userId === userId ||
            record.juniorScorer.isWaitDone === 1) &&
          templateData?.optionStatus === 9
        "
      >
        <a-textarea
          style="height: 100%"
          auto-size
          placeholder="评分说明"
          allow-clear
          v-model="
            tableData[record.indexRow].personnelKeyResultsIndexLibrary[
              record.indexLibrary
            ].scorer[record.juniorScorer.scoreIndex].note
          "
        />
      </div>
    </template>
    <template #otherScorerName="{ record }">
      {{ record.otherScorer?.userName }}
      {{
        record.otherScorer?.weight ? `(${record.otherScorer?.weight} %)` : ''
      }}
    </template>
    <template #otherScorerWeight="{ record }">
      {{
        record.scorerStatus?.other?.weight
          ? `${record.scorerStatus.other?.weight} %`
          : ''
      }}
    </template>
    <template #otherScorerMark="{ record }">
      <div
        v-if="
          props.args.showScoreInput &&
          record.otherScorer &&
          record.otherScorer.scoreIndex >= 0 &&
          (record.otherScorer.userId === userId ||
            record.otherScorer.isWaitDone === 1) &&
          templateData?.optionStatus === 9
        "
      >
        <a-input-number
          placeholder="评分"
          hide-button
          v-model="
            tableData[record.indexRow].personnelKeyResultsIndexLibrary[
              record.indexLibrary
            ].scorer[record.otherScorer.scoreIndex].score
          "
        />
      </div>
    </template>
    <template #otherScorerNote="{ record }">
      <div
        v-if="
          props.args.showScoreInput &&
          record.otherScorer &&
          record.otherScorer.scoreIndex >= 0 &&
          (record.otherScorer.userId === userId ||
            record.otherScorer.isWaitDone === 1) &&
          templateData?.optionStatus === 9
        "
      >
        <a-textarea
          style="height: 100%"
          auto-size
          placeholder="评分说明"
          allow-clear
          v-model="
            tableData[record.indexRow].personnelKeyResultsIndexLibrary[
              record.indexLibrary
            ].scorer[record.otherScorer.scoreIndex].note
          "
        />
      </div>
    </template>
    <template #indexLibrary="{ rowIndex }">
      <WeightInfo
        v-model:data="
          tempOkrData[rowIndex].personnelKeyResultsIndexLibrary[
            tempOkrData[rowIndex].indexLibrary
          ]
        "
      />
    </template>
    <template #returnReason="{ record }">
      <span v-if="props.args.showReason">
        {{ record.returnReason }}
      </span>
      <a-textarea
        v-else
        style="height: 100%"
        auto-size
        placeholder="退回原因"
        allow-clear
        v-model="tableData[record.indexRow].returnReason"
      />
    </template>
    <template #optional="{ rowIndex }">
      <a-tooltip content="设置评分人">
        <icon-user-add
          style="color: #3c6eff"
          :size="24"
          @click="setHuman(tempOkrData[rowIndex])"
        />
      </a-tooltip>
    </template>
    <template #scorer="{ record, rowIndex }">
      <a-tooltip content="编辑">
        <IconFont
          type="icon-edit"
          :size="26"
          :style="{
            marginRight: '10px',
            cursor: 'pointer'
          }"
          @click="goEdit(record, rowIndex)"
        />
      </a-tooltip>
      <a-tooltip content="删除" position="left">
        <a-popconfirm content="是否确认删除该条数据?" @ok="del(record)">
          <icon-font
            type="icon-delete"
            :size="26"
            :style="{
              cursor: 'pointer',
              marginRight: '10px'
            }"
          />
        </a-popconfirm>
      </a-tooltip>
    </template>
    <template #indexScore="{ record }">
      {{ record.score }}
    </template>
  </a-table>
  <a-button v-if="props.args.showAdd" type="text" @click="add">
    新增指标
  </a-button>
  <!-- <IndexDrawer
    v-model:visible="drawerVisible"
    @submit="submit"
    :data="currData"
  /> -->
  <IndexDrawer
    v-model:visible="drawerVisible"
    @okrIndexEmit="submit"
    :data="currData"
  />
  <ScoreHumanModal
    v-model:visible="humanVisible"
    v-model:data="currHumanData"
    @save="saveHUman"
    @del="delHUman"
    :index-type="6"
  />
</template>

<script setup lang="ts">
import { cloneDeep } from 'lodash';
import { PerformanceKeyPerformanceIndexLibraryUse } from '@/apis/management/performance/baseSetting/template/type';
import IndexDrawer from './IndexDrawer.vue';
// import IndexDrawer from '@/views/Management/Performance/BaseSetting/Index/OkrIndex/IndexDrawer.vue';
import WeightInfo from '../AbilityIndeTable/WeightInfo.vue';
import {
  PersonnelAbilityQualityIndexLibrary,
  ProbationExamine
} from '@/apis/human/base/variationManager/probation/type';
import ScoreHumanModal from '../AbilityIndeTable/ScoreHumanModal.vue';
import { delExamineToolInfo } from '@/apis/human/base/variationManager/probation';
import { useVModel } from '@vueuse/core';
import type { PersonnelIndexLibrary } from '@/apis/human/base/variationManager/probation/type';

const props = withDefaults(
  defineProps<{
    review?: number;
    data: PerformanceKeyPerformanceIndexLibraryUse[];
    upperLimitScore?: number;
    showRowSelection?: boolean;
    returnIndex?: PersonnelIndexLibrary;
    onlyShowSelected?: boolean; //只显示选中的数据
    returnTemp: number; //只显示选中的数据
    args?: {
      showAdd?: boolean; //显示新增
      showOperation?: boolean; //显示操作
      /**
       * 评分人显示样式。0集成，1区分不同评分人
       */
      scorerType?: number;
      /**
       * 是否显示分数输入框，默认false不开启，true开启
       */
      showScoreInput?: boolean;
      /**
       * 是否显示原因
       */
      showReason?: boolean;
      /**
       * 是否显示指标得分
       */
      showIndexScore?: boolean;
    };
    templateData?: ProbationExamine;
    delTargetData: any;
    selectedTargetIds?: number[];
  }>(),
  {
    args: () => ({
      showAdd: true,
      showOperation: true,
      scorerType: 0,
      showScoreInput: false,
      showReason: false,
      showIndexScore: true
    })
  }
);
const emit = defineEmits([
  'update:visible',
  'handleOk',
  'update:data',
  'update:delTargetData',
  'update:returnIndex',
  'update:selectedTargetIds'
]);
const handleOk = () => {
  emit('handleOk');
};
const change = () => {
  emit('update:data', tableData.value);
};
const tableData = useVModel(props, 'data', emit);
const returnData = useVModel(props, 'returnIndex', emit);
const delTargetData = useVModel(props, 'delTargetData', emit);
const selectedKeys = useVModel(props, 'selectedTargetIds', emit);
const columns = computed(() => {
  let colArr = [
    {
      title: '序号',
      dataIndex: 'index',
      slotName: 'index',
      width: 70,
      align: 'center'
    },
    {
      title: '目标（O）',
      dataIndex: 'name',
      width: 200,
      align: 'center'
    },
    {
      title: '关键成果(KRs)',
      dataIndex: 'achievementName',
      width: 200,
      align: 'center'
    },
    {
      title: '指标权重',
      dataIndex: 'achievementWeight',
      slotName: 'achievementWeight',
      width: 100,
      align: 'center'
    }
  ];

  if (!props.args.scorerType) {
    const maxScore = {
      title: '评分上限',
      dataIndex: 'maxScore',
      slotName: 'maxScore',
      width: 100,
      align: 'center'
    };
    const indexLibrary = {
      title: '评分人',
      dataIndex: 'indexLibrary',
      slotName: 'indexLibrary',
      width: 400,
      align: 'center'
    };
    colArr.splice(3, 0, maxScore);
    colArr.splice(5, 0, indexLibrary);
  } else {
    const owerScorer = {
      title: '员工自评',
      dataIndex: 'owerScorer',
      slotName: 'owerScorer',
      width: 200,
      align: 'center',
      children: [
        {
          title: '评分人',
          dataIndex: 'owerScorerName',
          slotName: 'owerScorerName',
          width: 200,
          align: 'center'
        },
        {
          title: '权重',
          dataIndex: 'owerScorerWeight',
          slotName: 'owerScorerWeight',
          width: 100,
          align: 'center'
        },
        {
          title: '评分',
          dataIndex: 'owerScorerMark',
          slotName: 'owerScorerMark',
          width: 100,
          align: 'center'
        },
        {
          title: '评分说明',
          dataIndex: 'owerScorerNote',
          slotName: 'owerScorerNote',
          width: 300,
          align: 'center'
        }
      ]
    };
    const appointScorer = {
      title: '指定人员',
      dataIndex: 'appointScorer',
      slotName: 'appointScorer',
      width: 200,
      align: 'center',
      children: [
        {
          title: '评分人',
          dataIndex: 'appointScorerName',
          slotName: 'appointScorerName',
          width: 200,
          align: 'center'
        },
        {
          title: '层级权重',
          dataIndex: 'appointScorerWeight',
          slotName: 'appointScorerWeight',
          width: 100,
          align: 'center'
        },
        {
          title: '评分',
          dataIndex: 'appointScorerMark',
          slotName: 'appointScorerMark',
          width: 100,
          align: 'center'
        },
        {
          title: '评分说明',
          dataIndex: 'appointScorerNote',
          slotName: 'appointScorerNote',
          width: 300,
          align: 'center'
        }
      ]
    };
    const superiorsScorer = {
      title: '上级',
      dataIndex: 'superiorsScorer',
      slotName: 'superiorsScorer',
      width: 200,
      align: 'center',
      children: [
        {
          title: '评分人',
          dataIndex: 'superiorsScorerName',
          slotName: 'superiorsScorerName',
          width: 200,
          align: 'center'
        },
        {
          title: '层级权重',
          dataIndex: 'superiorsScorerWeight',
          slotName: 'superiorsScorerWeight',
          width: 100,
          align: 'center'
        },
        {
          title: '评分',
          dataIndex: 'superiorsScorerMark',
          slotName: 'superiorsScorerMark',
          width: 100,
          align: 'center'
        },
        {
          title: '评分说明',
          dataIndex: 'superiorsScorerNote',
          slotName: 'superiorsScorerNote',
          width: 300,
          align: 'center'
        }
      ]
    };
    const juniorScorer = {
      title: '下级',
      dataIndex: 'juniorScorer',
      slotName: 'juniorScorer',
      width: 200,
      align: 'center',
      children: [
        {
          title: '评分人',
          dataIndex: 'juniorScorerName',
          slotName: 'juniorScorerName',
          width: 200,
          align: 'center'
        },
        {
          title: '层级权重',
          dataIndex: 'juniorScorerWeight',
          slotName: 'juniorScorerWeight',
          width: 100,
          align: 'center'
        },
        {
          title: '评分',
          dataIndex: 'juniorScorerMark',
          slotName: 'juniorScorerMark',
          width: 100,
          align: 'center'
        },
        {
          title: '评分说明',
          dataIndex: 'juniorScorerNote',
          slotName: 'juniorScorerNote',
          width: 300,
          align: 'center'
        }
      ]
    };
    const peerScorer = {
      title: '同级',
      dataIndex: 'peerScorer',
      slotName: 'peerScorer',
      width: 200,
      align: 'center',
      children: [
        {
          title: '评分人',
          dataIndex: 'peerScorerName',
          slotName: 'peerScorerName',
          width: 200,
          align: 'center'
        },
        {
          title: '层级权重',
          dataIndex: 'peerScorerWeight',
          slotName: 'peerScorerWeight',
          width: 100,
          align: 'center'
        },
        {
          title: '评分',
          dataIndex: 'peerScorerMark',
          slotName: 'peerScorerMark',
          width: 100,
          align: 'center'
        },
        {
          title: '评分说明',
          dataIndex: 'peerScorerNote',
          slotName: 'peerScorerNote',
          width: 300,
          align: 'center'
        }
      ]
    };
    const otherScorer = {
      title: '其他',
      dataIndex: 'otherScorer',
      slotName: 'otherScorer',
      width: 200,
      align: 'center',
      children: [
        {
          title: '评分人',
          dataIndex: 'otherScorerName',
          slotName: 'otherScorerName',
          width: 200,
          align: 'center'
        },
        {
          title: '层级权重',
          dataIndex: 'otherScorerWeight',
          slotName: 'otherScorerWeight',
          width: 100,
          align: 'center'
        },
        {
          title: '评分',
          dataIndex: 'otherScorerMark',
          slotName: 'otherScorerMark',
          width: 100,
          align: 'center'
        },
        {
          title: '评分说明',
          dataIndex: 'otherScorerNote',
          slotName: 'otherScorerNote',
          width: 300,
          align: 'center'
        }
      ]
    };
    const indexScore = {
      title: '指标得分',
      dataIndex: 'indexScore',
      slotName: 'indexScore',
      width: 100,
      align: 'center'
    };
    colArr.splice(6, 0, owerScorer);
    // colArr.splice(7, 0, appointScorer);
    // colArr.splice(8, 0, superiorsScorer);
    // colArr.splice(9, 0, juniorScorer);
    // colArr.splice(10, 0, peerScorer);
    // colArr.splice(11, 0, otherScorer);
    if (showTitle.appoit) colArr.push(appointScorer);
    if (showTitle.superiors) colArr.push(superiorsScorer);
    if (showTitle.junior) colArr.push(juniorScorer);
    if (showTitle.peer) colArr.push(peerScorer);
    if (showTitle.other) colArr.push(otherScorer);
    if (props.args.showIndexScore) colArr.push(indexScore);
  }

  if (props.returnTemp === 2 || props.args.showReason) {
    const returnReason = {
      title: '退回原因',
      dataIndex: 'returnReason',
      slotName: 'returnReason',
      fixed: 'right',
      width: 200,
      align: 'center'
    };
    colArr.push(returnReason);
  } else {
    const index = colArr.findIndex((item) => item.title === '退回原因');
    if (index >= 0) {
      colArr.splice(index, 1);
    }
  }
  if (props.args.showOperation) {
    //根据不同状态显示不同表格头和操作
    const scorer = {
      title: '操作',
      dataIndex: 'scorer',
      slotName: 'scorer',
      width: 120,
      align: 'center',
      fixed: 'right'
    };
    const optional = {
      title: '设置评分人',
      dataIndex: 'optional',
      slotName: 'optional',
      width: 110,
      fixed: 'right',
      align: 'center'
    };
    colArr.push(optional);
    colArr.push(scorer);
  }
  return colArr;
});

const userId = +localStorage.getItem('userId');
const currData = ref<PerformanceKeyPerformanceIndexLibraryUse>({});
const drawerVisible = ref(false);
const editIndex = ref(-1); //编辑项的下标，用以判断新增和编辑，下标小于0是新增数据。大于等于0则是修改此下标的值
const add = () => {
  editIndex.value = -1;
  currentIndex.value[0] = -1;
  currData.value = {
    weight: 0,
    status: 1,
    name: '',
    personnelKeyResultsIndexLibrary: [{ result: '', indexWeight: 0 }]
  };
  drawerVisible.value = true;
};

const goEdit = (data: any, index: number) => {
  editIndex.value = index;
  currData.value = data;
  drawerVisible.value = true;
  const { indexRow, indexLibrary } = data;
  currentIndex.value = [indexRow, indexLibrary];
};
const submit = (data: PerformanceKeyPerformanceIndexLibraryUse) => {
  if (!Array.isArray(tableData.value)) tableData.value = [data];

  //判断是新增还是编辑
  if (currentIndex.value[0] < 0) {
    //新增
    tableData.value.push(data);
  } else {
    //编辑
    if (!tableData.value?.length) return;

    tableData.value[currentIndex.value[0]] = data;
  }
  // change();
};
const showTitle = reactive({
  appoit: false,
  junior: false,
  other: false,
  peer: false,
  superiors: false
});
//表格显示的数据
let tempOkrData: any = computed(() => {
  let newArr: any = [];
  if (Array.isArray(tableData.value) && tableData.value?.length > 0) {
    let i = 1;
    tableData.value.forEach((item, index: number) => {
      if (
        props.onlyShowSelected &&
        !item.isReturn &&
        props.templateData?.optionStatus === 3
      ) {
        return;
      }
      if (index > 0 && tableData.value[index - 1]?.name === item?.name) {
        if (item) {
          item.index = tableData.value[index - 1]?.index;
        }
      } else {
        item.index = i;
        i++;
      }
      item?.personnelKeyResultsIndexLibrary?.forEach(
        (item2, index2: number) => {
          let result: any = {
            ...item2,
            achievementName: item2.result,
            achievementWeight: item2.indexWeight,
            indexLibrary: index2,
            indexRow: index,
            id: item.id,
            name: item.name
          };
          if (!item2?.scorer?.length) {
            newArr.push({ ...result });
            return;
          }
          result = { ...item, ...result };
          if (props.args.scorerType === 1) {
            const appointScorer: any[] = [];
            const superiorsScorer: any[] = [];
            const juniorScorer: any[] = [];
            const peerScorer: any[] = [];
            const owerScorer: any[] = [];
            const otherScorer: any[] = [];
            item2?.scorer?.forEach((scorer, scoreIndex: any) => {
              if (scorer.type && scorer.type > 0) {
                scorer.scoreIndex = scoreIndex;
                if (scorer.type === 1) {
                  appointScorer.push(scorer);
                  showTitle.appoit = true;
                }
                if (scorer.type === 2) {
                  superiorsScorer.push(scorer);
                  showTitle.superiors = true;
                }
                if (scorer.type === 3) {
                  peerScorer.push(scorer);
                  showTitle.peer = true;
                }
                if (scorer.type === 4) {
                  juniorScorer.push(scorer);
                  showTitle.junior = true;
                }
                if (scorer.type === 5) {
                  owerScorer.push(scorer);
                }
                if (scorer.type === 6) {
                  otherScorer.push(scorer);
                  showTitle.other = true;
                }
              }
            });
            //获取最大值，得出需要合并多少格
            const maxLength = Math.max(
              appointScorer.length,
              superiorsScorer.length,
              juniorScorer.length,
              peerScorer.length,
              owerScorer.length,
              otherScorer.length
            );
            for (let n = 0; n < maxLength; n++) {
              const scorerArr = {
                appointScorer: appointScorer[n],
                superiorsScorer: superiorsScorer[n],
                juniorScorer: juniorScorer[n],
                peerScorer: peerScorer[n],
                owerScorer: owerScorer[n],
                otherScorer: otherScorer[n]
              };
              const resultRowspan = n === 0 ? maxLength : 0;
              newArr.push({
                ...result,
                ...scorerArr,
                resultRowspan,
                tableIndex: index
              });
            }
          } else {
            newArr.push({ ...result });
          }
        }
      );
    });
    console.log('newArr', newArr);

    return newArr;
  } else return [];
});
// 表格合并
const dataSpanMethod = (datas: any) => {
  const { record, rowIndex, columnIndex, column } = datas;
  // 处理rowSpan
  const obj = {
    rowspan: 2,
    colspan: 1
  };
  const enums = [
    'achievementName',
    'achievementWeight',
    'indexLibrary',
    'optional',
    'indexScore'
  ];
  const enums2 = [
    'achievementName',
    'achievementWeight',
    'optional',
    'appointScorerWeight',
    'otherScorerWeight',
    'peerScorerWeight',
    'juniorScorerWeight',
    'superiorsScorerWeight',
    'owerScorerName',
    'owerScorerWeight',
    'owerScorerMark',
    'owerScorerNote'
  ];
  if (props.args.scorerType) {
    if (record.resultRowspan && enums2.includes(column.dataIndex)) {
      return {
        rowspan: record.resultRowspan
        // colspan: 1
      };
    }
    if (
      columnIndex === 0 &&
      tempOkrData.value[rowIndex - 1]?.name !== record?.name
    ) {
      let arr = tempOkrData.value.filter(
        (item: any) => item?.name === record?.name
      );

      obj.rowspan = arr?.length;
      return obj;
    }
    if (
      ['name', 'index', 'returnReason', 'scorer', 'indexScore'].includes(
        column.dataIndex
      ) &&
      tempOkrData.value[rowIndex - 1]?.name !== record?.name
    ) {
      let arr = tempOkrData.value.filter(
        (item: any) => item?.name === record?.name
      );
      obj.rowspan = arr?.length;
    } else {
      obj.rowspan = 0;
    }
  } else {
    let arr = tempOkrData.value.filter(
      (item: any) => item?.name === record?.name
    );
    if (
      !enums.includes(column.dataIndex) &&
      tempOkrData.value[rowIndex - 1]?.name !== record?.name
    ) {
      obj.rowspan = arr?.length;
    } else {
      obj.rowspan = 0;
    }
  }

  return obj;
};

const humanVisible = ref(false);
const currHumanData = ref<PersonnelAbilityQualityIndexLibrary>();
const currentIndex = ref<any[]>([]);
const setHuman = (data: any, index?: number) => {
  const { indexRow, indexLibrary } = data;

  let dataIndexLibrary =
    tableData.value[indexRow].personnelKeyResultsIndexLibrary[indexLibrary];
  dataIndexLibrary.scorer = dataIndexLibrary.scorer
    ? dataIndexLibrary.scorer
    : [];
  dataIndexLibrary.scorerStatus = dataIndexLibrary.scorerStatus || {
    appoint: { status: 2, weight: 0 },
    superiors: { status: 2, weight: 0 },
    junior: { status: 2, weight: 0 },
    peer: { status: 2, weight: 0 },
    other: { status: 2, weight: 0 }
  };

  console.log('data', index);
  humanVisible.value = true;
  currentIndex.value = [indexRow, indexLibrary];
  currHumanData.value = cloneDeep(dataIndexLibrary);
};
const saveHUman = () => {
  if (!tableData.value?.length) return;
  const indexRow = currentIndex.value[0];
  const indexLibrary = currentIndex.value[1];
  tableData.value[indexRow].personnelKeyResultsIndexLibrary[indexLibrary] =
    currHumanData.value;
  humanVisible.value = false;
};
const delHUman = () => {
  if (!tableData.value?.length) return;
  tableData.value[currentIndex.value[0]] = currHumanData.value;
  // humanVisible.value = false;
};
const del = async (data: any) => {
  let index = data.indexRow;
  if (!tableData.value?.length) return;
  const { id } = tableData.value[index];
  if (props?.templateData?.optionStatus === 5) {
    if (id > 0) {
      delTargetData.value.push({ ...tableData.value[index] });
    }
    tableData.value.splice(index, 1);
    return;
  }

  if (id > 0) {
    await delExamineToolInfo({ ids: [id], type: 6 });
  }
  tableData.value.splice(index, 1);
  // change();
};
const select = (rowKeys: any, rowKey: any, record: any) => {
  if (selectedKeys.value?.includes(record.id)) {
    selectedKeys.value = selectedKeys.value.filter(
      (item) => item !== record.id
    );
  } else {
    selectedKeys.value?.push(record.id);
  }
  record.isReturn = !record.isReturn;
  const index = tableData.value.findIndex((item) => item.id === rowKey);
  if (index >= 0) {
    tableData.value[index].isReturn = !tableData.value[index].isReturn;
  }
  // console.log('rowKeys', rowKeys);
  // console.log('rowKey', rowKey);
  // console.log('record', record);
};
</script>

<style lang="less" scoped>
.add {
  border-left: 2px solid #00b42a;
}
.update {
  border-left: 2px solid #165dff;
}
.del {
  border-left: 2px solid #f53f3f;
}
</style>
